<?php
/**
 * Class Order
 * Desc  订单api
 * Create on 2021/8/18 15:39
 * Create by wangyafang
 */

namespace app\api\controller\xyb;

use addons\epay\library\Service;
use addons\xyb\XypHelper;
use app\admin\model\xyb\system\Config;
use app\api\model\xyb\OrderReward;
use app\api\model\xyb\Profit;
use app\api\model\xyb\UserPlat;
use app\api\model\xyb\Wallets;
use app\api\service\OrdersService;
use app\api\service\PaymentService;
use app\api\service\UsersService;
use app\common\model\marketing\UsersMarketingCoupons;
use app\common\model\Refund;
use app\common\model\Voucher;
use app\common\model\xyb\AdminBelong;
use app\common\model\xyb\MiniPushMessageLog;
use app\common\model\xyb\UserBelong;
use think\Cache;
use think\cache\driver\Redis;
use think\Db;
use app\api\model\xyb\OrderReceive;
use app\api\model\xyb\Express;
use app\api\model\xyb\Server;

use think\Exception;
use think\Log;
use Yansongda\Pay\Pay;

class Order extends Base
{
    protected $noNeedLogin = [''];

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\xyb\Order();
    }

    /**
     * desc:发布跑腿任务
     */
    public function push_run_errands()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $type = request()->param('type', 1);
        $users = $this->getAuthUsers();
        $agent_info = UsersService::getCommunityWhereUsersLocated($users->id);
        $param = $_POST;
        $param['order_no'] = XypHelper::xyb_get_order_no();
        $param['user_id'] = $users->id;
        $param['agent_id'] = $agent_info->agent_id;
        $param['type'] = $type;
        $param['status'] = 0;
        $param['pay'] = 0;
        $param['coupons_id'] = isset($_POST['coupons_id'])?intval($_POST['coupons_id']):0;
        $param['discount'] = 0;
        $param['price'] = floatval($param['price']);
        $param['createtime'] = time();
        $param['app_plat'] = 'MP-WEIXIN';
        $param['total_fee'] = (float)$param['price'];
        $param['pay_fee'] = (float)$param['price'];
        if(isset($param['coupons_id']) && $param['coupons_id']){
            $coupons_detail = UsersMarketingCoupons::getUsersCouponsPaymentCanBeUsed(
                $param['user_id'], $param['total_fee'], $param['coupons_id'], 2, ($param['type'] + 1)
            );
            if (!$coupons_detail) {
                $this->error('优惠券不可用');
            }
            if (!isset($coupons_detail['discount_amount']) || !$coupons_detail['discount_amount']) {
                $this->error('优惠券不可用');
            }
            $param['coupons_id'] = $coupons_detail->id;
            $param['discount'] = (float)$coupons_detail['discount_amount'];
            $param['pay_fee'] = ($param['total_fee'] - $param['discount']);
        }
        $result = $this->checkType($param['type'], $param);
        if (true !== $result) {
            $this->error($result);
        }
        $insert_result = $this->model->allowField(true)->save($param);
        if ($insert_result) {
            if($param['coupons_id']){
                UsersMarketingCoupons::usersUsedCoupons($param['user_id'], $param['coupons_id'], $this->model->id, $param['discount'], 2,$param['total_fee']);
            }
            $this->success('创建订单成功', ['id' => $this->model->id]);
        } else {
            $this->error('创建订单失败');
        }
    }

    /**
     * desc:发布取快递任务
     */
    public function push_run_express()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $agent_info = UsersService::getCommunityWhereUsersLocated($users->id);
        $param = $_POST;
        $param['order_no'] = XypHelper::xyb_get_order_no();
        $param['user_id'] = $users->id;
        $param['agent_id'] = $agent_info->agent_id;
        $param['coupons_id'] =isset($_POST['coupons_id'])?intval($_POST['coupons_id']):0;
        $param['type'] = 2;
        $param['status'] = 0;
        $param['pay'] = 0;
        $param['createtime'] = time();
        $param['app_plat'] = 'MP-WEIXIN';
        $param['reward'] = 0;
        //  $param['total_fee'] = $param['price'];

        $result = $this->checkType($param['type'], $param);
        $tem = 0;
        if (empty($param['reward'])) {
            $param['reward'] = 0;
        }
        $express_array = json_decode($param['express'], true);
        foreach ($express_array as $k => $v) {
            $tem = bcadd($tem, bcmul($v['price'], $v['number'], 2), 2);
        }
        $param['total_fee'] = bcadd($tem, $param['reward'], 2);
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        if(isset($param['coupons_id']) && $param['coupons_id']){
            $coupons_detail = UsersMarketingCoupons::getUsersCouponsPaymentCanBeUsed(
                $param['user_id'], $param['total_fee'], $param['coupons_id'], 2, ($param['type'] + 1)
            );
            if (!$coupons_detail) {
                $this->error('优惠券不可用');
            }
            if (!isset($coupons_detail['discount_amount']) || !$coupons_detail['discount_amount']) {
                $this->error('优惠券不可用');
            }
            $param['coupons_id'] = $coupons_detail->id;
            $param['discount'] = (float)$coupons_detail['discount_amount'];
            $param['pay_fee'] = ($param['total_fee'] - $param['discount']);
        }
        $insert_result = $this->model->allowField(true)->save($param);
        if ($insert_result) {
            if($param['coupons_id']){
                UsersMarketingCoupons::usersUsedCoupons($param['user_id'], $param['coupons_id'], $this->model->id, $param['discount'], 2, $param['total_fee']);
            }
            $this->success('创建订单成功', [
                'id' => $this->model->id
            ]);
        } else {
            $this->error('创建订单失败');
        }
    }

    /**
     * desc:发布帮我取
     */
    public function push_help_retrieve()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $agent_info = UsersService::getCommunityWhereUsersLocated($users->id);
        $param = $_POST;
        $param['order_no'] = XypHelper::xyb_get_order_no();
        $param['user_id'] = $users->id;
        $param['agent_id'] = $agent_info->agent_id;
        $param['coupons_id'] =isset($_POST['coupons_id'])?intval($_POST['coupons_id']):0;
        $param['type'] = 2;
        $param['status'] = 0;
        $param['pay'] = 0;
        $param['createtime'] = time();
        $param['app_plat'] = 'MP-WEIXIN';
        $param['reward'] = 0;
        //  $param['total_fee'] = $param['price'];

        $result = $this->checkType($param['type'], $param);
        $tem = 0;
        if (empty($param['reward'])) {
            $param['reward'] = 0;
        }
        $express_array = json_decode($param['express'], true);
        foreach ($express_array as $k => $v) {
            $tem = bcadd($tem, bcmul($v['price'], $v['number'], 2), 2);
        }
        $param['total_fee'] = bcadd($tem, $param['reward'], 2);
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        if(isset($param['coupons_id']) && $param['coupons_id']){
            $coupons_detail = UsersMarketingCoupons::getUsersCouponsPaymentCanBeUsed(
                $param['user_id'], $param['total_fee'], $param['coupons_id'], 2, ($param['type'] + 1)
            );
            if (!$coupons_detail) {
                $this->error('优惠券不可用');
            }
            if (!isset($coupons_detail['discount_amount']) || !$coupons_detail['discount_amount']) {
                $this->error('优惠券不可用');
            }
            $param['coupons_id'] = $coupons_detail->id;
            $param['discount'] = (float)$coupons_detail['discount_amount'];
            $param['pay_fee'] = ($param['total_fee'] - $param['discount']);
        }
        $insert_result = $this->model->allowField(true)->save($param);
        if ($insert_result) {
            if($param['coupons_id']){
                UsersMarketingCoupons::usersUsedCoupons($param['user_id'], $param['coupons_id'], $this->model->id, $param['discount'], 2, $param['total_fee']);
            }
            $this->success('创建订单成功', [
                'id' => $this->model->id
            ]);
        } else {
            $this->error('创建订单失败');
        }
    }

    /**
     * desc:发布帮我取
     */
    public function push_do_handle()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $users = $this->getAuthUsers();
        $agent_info = UsersService::getCommunityWhereUsersLocated($users->id);
        $param = $_POST;
        $param['order_no'] = XypHelper::xyb_get_order_no();
        $param['user_id'] = $users->id;
        $param['agent_id'] = $agent_info->agent_id;
        $param['coupons_id'] =isset($_POST['coupons_id'])?intval($_POST['coupons_id']):0;
        $param['type'] = 2;
        $param['status'] = 0;
        $param['pay'] = 0;
        $param['createtime'] = time();
        $param['app_plat'] = 'MP-WEIXIN';
        $param['reward'] = 0;
        //  $param['total_fee'] = $param['price'];

        $result = $this->checkType($param['type'], $param);
        $tem = 0;
        if (empty($param['reward'])) {
            $param['reward'] = 0;
        }
        $express_array = json_decode($param['express'], true);
        foreach ($express_array as $k => $v) {
            $tem = bcadd($tem, bcmul($v['price'], $v['number'], 2), 2);
        }
        $param['total_fee'] = bcadd($tem, $param['reward'], 2);
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        if(isset($param['coupons_id']) && $param['coupons_id']){
            $coupons_detail = UsersMarketingCoupons::getUsersCouponsPaymentCanBeUsed(
                $param['user_id'], $param['total_fee'], $param['coupons_id'], 2, ($param['type'] + 1)
            );
            if (!$coupons_detail) {
                $this->error('优惠券不可用');
            }
            if (!isset($coupons_detail['discount_amount']) || !$coupons_detail['discount_amount']) {
                $this->error('优惠券不可用');
            }
            $param['coupons_id'] = $coupons_detail->id;
            $param['discount'] = (float)$coupons_detail['discount_amount'];
            $param['pay_fee'] = ($param['total_fee'] - $param['discount']);
        }
        $insert_result = $this->model->allowField(true)->save($param);
        if ($insert_result) {
            if($param['coupons_id']){
                UsersMarketingCoupons::usersUsedCoupons($param['user_id'], $param['coupons_id'], $this->model->id, $param['discount'], 2, $param['total_fee']);
            }
            $this->success('创建订单成功', [
                'id' => $this->model->id
            ]);
        } else {
            $this->error('创建订单失败');
        }
    }

    /**
     * desc:订单详情
     */
    public function pull_orders_detail()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $order_id = $this->request->param('id');
        $field = 'id,order_no,receive_id,user_id,status,type,start,destination,information,total_fee,reward,price,is_complaint,';
        $field .= 'express,remarks,annex_information_images,hope_arrive,pay,pay_time,receive_time,complete_time,cancel_time,';
        $field .= 'send_time,createtime,receive_limit,mobile,notes,send_picture,package_time,package_picture,pick_code,agent_id,';
        $field .= 'evaluate,evaluate_time,is_complaint,pay_fee,discount,coupons_id';
        $data = Db::name('xyb_order')->where('id', $order_id)->field($field)->find();
        if (!$data) {
            $this->error('订单不存在');
        }
        $data['nickname'] = '';
        $data['avatar'] = '';
        $data['receiving_nickname'] = '';
        $data['receiving_avatar'] = '';
        $data['receiving_mobile'] = '';
        /*获取发布人的用户信息*/
        if ($push_users = UsersService::getUsersFoundation($data['user_id'])) {
            $data['nickname'] = $push_users['nickname'];
            $data['avatar'] = $push_users['avatar'];
        }
        /*获取接单人的用户信息*/
        if ($receiving_users = UsersService::getReceivingUsersFoundation($data['receive_id'], $data['agent_id'])) {
            $data['receiving_nickname'] = $receiving_users['nickname'];
            $data['receiving_avatar'] = $receiving_users['avatar'];
            $data['receiving_mobile'] = $receiving_users['mobile'];
            $data['receiving_evaluate'] = $receiving_users['evaluate'];
        }
        /*处理佣金*/
        $data['amount_items'] = OrdersService::CalculateOrdersRevenue($data);
        $data['receive_amount'] = $data['amount_items']['receive_amount'];
        /*处理状态信息*/
        $data['status_text'] = OrdersService::formatOrdersStatus($data['status']);
        if ($data['notes'] == 'null' || is_null($data['notes'])) {
            $data['notes'] = '';
        }
        $data['coupons_id'] = intval($data['coupons_id']);
        $data['coupons_detail'] = [];
        if ($data['coupons_id']) {
            $data['coupons_detail'] = UsersMarketingCoupons::getUsersCouponsDetails($data['coupons_id']);
        }
        /*处理时间*/
        $data['create_date'] = date("Y-m-d H:i:s", $data['createtime']);
        $data['pay_date'] = $data['pay_time'] ? date("Y-m-d H:i:s", $data['pay_time']) : '';
        $data['receive_date'] = $data['receive_time'] ? date("Y-m-d H:i:s", $data['receive_time']) : '';
        $data['package_date'] = $data['package_time'] ? date("Y-m-d H:i:s", $data['package_time']) : '';
        $data['send_date'] = $data['send_time'] ? date("Y-m-d H:i:s", $data['send_time']) : '';
        $data['complete_date'] = $data['complete_time'] ? date("Y-m-d H:i:s", $data['complete_time']) : '';
        $data['type_text'] = $this->model->getTypeTextAttr($data['type'], []);
        $data['dateline_create_date'] = XypHelper::xyb_dateline($data['createtime']);//创建时间
        $data['annex_information_images'] = XypHelper::stringToArray($data['annex_information_images']);
        $data['send_picture'] = XypHelper::stringToArray($data['send_picture']);
        $data['package_picture'] = XypHelper::stringToArray($data['package_picture']);
        $data['express'] = !empty($data['express']) ? json_decode($data['express']) : [];
        $data['is_pick_code'] = OrdersService::getAgentAdminBelongIspickCode($data['agent_id']);
        $this->success('请求成功', $data);
    }

    /**
     * desc:未支付订单取消
     */
    public function unpaid_cancel()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        if (!$order_id = (int)$this->request->param('id')) {
            $this->error('订单不存在');
        }
        $operate_cache_key = '__operate_order_' . $order_id;
        if (Cache::get($operate_cache_key)) {
            $this->error('订单正在操作中，请稍后再试！');
        }
        Cache::set($operate_cache_key, 1, 60);
        $field = 'id,order_no,user_id,status,type,information,createtime,pay_time,receive_time,send_time,notes,complete_time,mobile,coupons_id';
        $order = Db::name('xyb_order')->where('id', $order_id)->field($field)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        $this->model->save(['status' => '4', 'cancel_time' => time(), 'updatetime' => time()], ['id' => $order_id]);
        if (isset($order['coupons_id']) && $order['coupons_id']) {
            UsersMarketingCoupons::returnUsersCoupons($order['user_id'], $order['coupons_id'], $order_id);
        }
        Cache::rm($operate_cache_key);
        $this->success('订单取消成功');
    }

    /**
     * @throws \Exception
     * @desc 调起小程序微信支付
     */
    public function wx_minapp_pay()
    {
        $users = $this->getAuthUsers();
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $order_id = $this->request->param('id');
        $coupons_id = $this->request->param('coupons_id');
        $field = 'id,user_id,order_no,status,type,pay,pay_time,total_fee,pay_fee,coupons_id,discount,price,coupons_id';
        $data = Db::name('xyb_order')->where('id', $order_id)->field($field)->find();
        if (!$data) {
            $this->error('订单不存在');
        }
        if ($data['pay'] == 1 && $data['pay_time'] && $data['status'] == 1) {
            $this->error('订单已支付');
        }
        if (!$data['total_fee']) {
            $this->error('支付价格和订单价格不一致');
        }
       // $pay_fee = $data['total_fee'];
        $pay_fee = (float)$data['pay_fee'];
        $discount = 0;
        $coupons_detail = [];
        $user_coupons_id = 0;
//        if ($coupons_id && !$data['discount']) {
//            $coupons_detail = UsersMarketingCoupons::getUsersCouponsPaymentCanBeUsed($data['user_id'], $data['price'], $coupons_id, 2, ($data['type'] + 1));
//            if (!$coupons_detail) {
//                $this->error('优惠券不可用');
//            }
//            $user_coupons_id = $coupons_detail->id;
//            if (!isset($coupons_detail['discount_amount']) || !$coupons_detail['discount_amount']) {
//                $this->error('优惠券不可用');
//            }
//            $discount = (float)$coupons_detail['discount_amount'];
//            $pay_fee = ($pay_fee - $discount);
//        } else {
//            $user_coupons_id = (int)$data['coupons_id'];
//            $discount = (float)$data['discount'];
//            $pay_fee = (float)($data['total_fee']) - (float)$data['discount'];
//        }
        $type_text = $this->model->getTypeTextAttr($data['type'], []);
        $title = $type_text . ' —— ' . $this->configObj->miniapp_title;
        $pay_order_no = XypHelper::xyb_get_order_no(); //$data['total_fee']
        $payment = PaymentService::orders($order_id, $pay_order_no, $users->miniapp_openid, $pay_fee, $title);
        $this->model->save([
            'wechat_pay_prepare' => json_encode($payment, JSON_UNESCAPED_UNICODE),
            'pay_order_no' => $pay_order_no,
            //'coupons_id' => $user_coupons_id,
           // 'pay_fee' => $pay_fee,
           // 'discount' => $discount,
            'updatetime' => time()
        ], ['id' => $order_id]);
        $this->success('订单拉取成功', [
            'payment' => $payment,
            'order_id' => (int)$order_id,
            'type' => 1,
          //  '_coupons' => $coupons_detail,
            'pay_stated' => false
        ]);
    }

    /**
     * @throws \Exception
     * @desc 打赏骑手
     */
    public function order_reward()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        if (!$order_id = $this->request->param('id')) {
            $this->error('订单不存在');
        }
        $operate_cache_key = '__operate_order_' . $order_id;
        if (!$reward = (int)$this->request->param('reward')) {
            $this->error('打赏金额错误');
        }
        $users = $this->getAuthUsers();
        $field = 'id,user_id,order_no,status,type,pay,pay_time,total_fee,agent_id,receive_id';
        $data = Db::name('xyb_order')->where('id', $order_id)->field($field)->find();
        if (!$data) {
            $this->error('订单不存在');
        }
        if (!$data['pay']) {
            $this->error('订单未支付');
        }
        Db::startTrans();
        if (!$order_reward = OrderReward::createOrderReward($data, $reward)) {
            Db::rollback();
            $this->error('订单打赏失败');
        }
        $type_text = $this->model->getTypeTextAttr($data['type'], []);
        $title = $type_text . ' —— ' . $this->configObj->miniapp_title;
        $payment = PaymentService::reward($order_reward->id, $order_reward->pay_order_no, $users->miniapp_openid, (float)$order_reward->total_fee, $title);
        $order_reward->wechat_pay_prepare = json_encode($payment, JSON_UNESCAPED_UNICODE);
        if (!$order_reward->save()) {
            Db::rollback();
            $this->error('订单打赏失败');
        }
        Db::commit();
        Cache::rm($operate_cache_key);
        $this->success('支付拉取成功', [
            'payment' => $payment,
            'order_id' => (int)$order_reward->id,
            'type' => 2,
            'pay_stated' => false
        ]);
    }

    /*检查订单*/
    public function check_orders_payment()
    {
        $users = $this->getAuthUsers();
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $order_id = $this->request->param('id');
        $type = $this->request->param('type', 1);
        $field = 'id,user_id,order_no,status,type,pay_time,status,pay';
        $data = Db::name('xyb_order')->where('id', $order_id)->field($field)->find();
        if (!$data) {
            $this->error('订单不存在');
        }
        if ($type == 1) {
            if ($data['pay'] == 1 && $data['pay_time'] && $data['status'] == 1) {
                $this->success('订单已支付', ['pay_stated' => true, 'order_id' => $order_id]);
            } else {
                $this->error('订单未支付', ['pay_stated' => false, 'order_id' => $order_id]);
            }
        } else {
            if (OrderReward::checkOrderPayment($order_id)) {
                $this->success('订单打赏已支付', ['pay_stated' => true, 'order_id' => $order_id]);
            } else {
                $this->error('订单打赏未支付', ['pay_stated' => false, 'order_id' => $order_id]);
            }
        }
    }

    /*订单退款*/
    public function refund()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        if (!$order_id = $this->request->param('id')) {
            $this->error('订单不存在');
        }
        $tags = $this->request->param('tags');
//        $reason = $this->request->param('refund_reason');
        $operate_cache_key = '__operate_order_' . $order_id;
        if (Cache::get($operate_cache_key)) {
            $this->error('订单正在操作中，请稍后再试！');
        }
        Cache::set($operate_cache_key, $order_id, 5);
        $field = 'id,user_id,order_no,status,type,pay,pay_time,total_fee,pay_order_no,reward,price,coupons_id,pay_fee';
        $order = Db::name('xyb_order')->where('id', $order_id)->field($field)->find();
        $param = $this->request->param();
        if (!$order) {
            Cache::rm($operate_cache_key);
            $this->error('订单不存在');
        }
        if (!$order['pay']) {
            $this->error('订单未支付');
        }
        if ($order['status'] != 1) {
            $this->error('订单已取消，请务重复操作');
        }
        Db::startTrans();
        try {
            /*订单退款*/
            $notify_url = $this->request->domain() . '/api/order/refundnotifyx';//退款回调地址
            $refund_sn = XypHelper::xyb_get_refund_sn($order['user_id']);
            $response = WxPay::submitRefund(
                $order['pay_fee'], $order['pay_fee'], $order['pay_order_no'], $refund_sn, 'wechat',
                '用户取消订单', $notify_url, '', 'miniapp'
            );
            Log::info($response);
            if (!isset($response->return_code) || $response->return_code != 'SUCCESS') {
                Db::rollback();
                $this->error('订单退款失败，请联系客服');
            }
            Db::name('xyb_order')->where('id', $order_id)->update(['status' => 6, 'refund_tags' => $tags, 'updatetime' => time()]);
            if (isset($order['coupons_id']) && $order['coupons_id']) {
                UsersMarketingCoupons::returnUsersCoupons($order['user_id'], $order['coupons_id'], $order_id);
            }
            /*小费退款*/
            if ($order_reward = OrderReward::getOrderPaymentRewardLists($order_id)) {
                foreach ($order_reward as $value) {
                    $refund_sn = XypHelper::xyb_get_refund_sn($value['user_id']);
                    $response = WxPay::submitRefund(
                        $value['total_fee'], $value['total_fee'], $value['pay_order_no'], $refund_sn, 'wechat',
                        '用户取消订单', $notify_url, '', 'miniapp'
                    );
                    Log::info($response);
                    if (!isset($response->return_code) || $response->return_code != 'SUCCESS') {
                        Db::rollback();
                        $this->error('订单退款失败，请联系客服');
                    }
                    $res = OrderReward::where(['id' => $value['id']])->update(['status' => 6, 'updatetime' => time()]);
                    if (!$res) {
                        Db::rollback();
                        $this->error('订单退款失败');
                    }
                }
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Cache::rm($operate_cache_key);
        Db::commit();
        $this->success('退款成功');
    }

    /**
     * desc:创建订单
     */
    public function create()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $_POST;
        $param['order_no'] = XypHelper::xyb_get_order_no();
        $param['user_id'] = $this->auth->id;
        $result = $this->checkType($param['type'], $param);
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        if ($param['type'] == 2) {
            $tem = 0;
            $express_array = json_decode($param['express'], true);
            foreach ($express_array as $k => $v) {
                $tem = bcadd($tem, bcmul($v['price'], $v['number'], 2), 2);
            }
            if (empty($param['reward'])) {
                $param['reward'] = 0;
            }
            $param['total_fee'] = bcadd($tem, $param['reward'], 2);
        }
        $insert_result = $this->model->allowField(true)->save($param);
        if ($insert_result) {
            $this->success('创建订单成功', ['id' => $this->model->id]);
        } else {
            $this->error('创建订单失败');
        }
    }

    /*检查类型参数*/
    protected function checkType($value, $data)
    {
        $order_min_amount = (new Config())->value('order_min_amount');
        switch ($value) {
            case 2:
                if (empty($data['start'])) {
                    return '请填写取货地点';
                }
                if (empty($data['destination'])) {
                    return '请选择收货地址';
                }
                if (empty($data['express'])) {
                    return '请选择物品属性';
                }
                break;
            case 1:
            case 3:
                if (empty($data['start'])) {
                    return '请填写取货地点';
                }
                if (empty($data['destination'])) {
                    return '请选择收货地址';
                }
                if (empty($data['hope_arrive'])) {
                    return '请选择送达时间';
                }
//                if (empty($data['information'])) {
//                    return '请填写帮助内容';
//                }
                if (empty($data['price'])) {
                    return '请填写跑腿费';
                }
                if ($data['price'] < $order_min_amount) {
                    return '订单最低金额不能低于' . $order_min_amount . '元';
                }
                if (!$data['mobile']) {
                    return '请填写手机号码';
                }
                break;
            case 4:
                if (empty($data['start'])) {
                    return '请填写取货地点';
                }
                if (empty($data['hope_arrive'])) {
                    return '请选择送达时间';
                }
//                if (empty($data['information'])) {
//                    return '请填写帮助内容';
//                }
                if (empty($data['price'])) {
                    return '请填写跑腿费';
                }
                if ($data['price'] < $order_min_amount) {
                    return '订单最低金额不能低于' . $order_min_amount . '元';
                }
                if (!$data['mobile']) {
                    return '请填写手机号码';
                }
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * 列表
     */
    public function index()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->param();
        $where = [];
        if ($param['eq_status'] != '') {
            if ($param['eq_status'] == 2) {
                $where['status'] = array('in', [2, 7]);
            } else {
                $where['status'] = array('eq', $param['eq_status']);
            }
        }
        if (isset($param['agent_id']) && $param['agent_id']) {
            $where['agent_id'] = array('eq', $param['agent_id']);
        }
        $where['user_id'] = array('eq', $this->auth->id);
        $count = $this->model->where($where)->count();

        $data = $this->model->where($where)
            ->alias('order')
            ->page($param['page'], $param['limit'])
            ->order('order.id desc')
            ->field("order.*")
            ->select();
        $app_plat = $this->request->param('app_plat');
        foreach ($data as $k => $v) {
            $data[$k]['time'] = XypHelper::xyb_dateline($v['createtime']);
            switch ($app_plat) {
                case 'MP-WEIXIN':
                    $wechatInfo = Db::name('xyb_user_plat')
                        ->alias('u_p')
                        ->where('u_p.user_id', $v['user_id'])
                        ->join('xyb_user_wechat u_w', 'u_w.id = u_p.wechat_id')
                        ->field('u_w.nickname,u_w.avatar')
                        ->find();
                    $data[$k]['nickname'] = $wechatInfo['nickname'];
                    $data[$k]['avatar'] = XypHelper::xyb_full_url($wechatInfo['avatar']);
                    break;
            }
        }
        $this->success('请求成功', ['total' => $count, 'data' => $data]);
    }


    /**
     * desc:订单详情
     */
    public function user_detail()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $id = $this->request->param('orderid');
        var_dump($id);
        exit;
        $app_plat = $this->request->param('app_plat');
        $type = $this->model->where('id', $id)->value('type');
        $receive_id = (new OrderReceive())->where('order_id', $id)->value('receive_id');
        $field = '*';
        $data = Db::name('xyb_order')->where('id', $id)->field($field)->find();
        switch ($app_plat) {
            case 'MP-WEIXIN':
                $wechatInfo = Db::name('xyb_user_plat')
                    ->alias('u_p')
                    ->where('u_p.user_id', $data['user_id'])
                    ->join('xyb_user_wechat u_w', 'u_w.id = u_p.wechat_id')
                    ->field('u_w.nickname,u_w.avatar')
                    ->find();
                $data['nickname'] = $wechatInfo['nickname'];
                $data['avatar'] = XypHelper::xyb_full_url($wechatInfo['avatar']);
                if (!$receive_id) {
                    $data['receive'] = [];
                } else {
                    $receiveInfo = Db::name('xyb_user_plat')
                        ->alias('u_p')
                        ->where('u_p.user_id', $receive_id)
                        ->join('xyb_user_wechat u_w', 'u_w.id = u_p.wechat_id')
                        ->field('u_w.nickname,u_w.avatar,u_p.mobile')
                        ->find();
                    $data['receive'] = array(
                        'nickname' => $receiveInfo['nickname'],
                        'avatar' => XypHelper::xyb_full_url($receiveInfo['avatar']),
                        'mobile' => $receiveInfo['mobile'],
                    );
                }
                break;
        }
        unset($data['user_id']);
        $data['createtime'] = date("Y-m-d H:i:s", $data['createtime']);
        $data['type_text'] = $this->model->getTypeTextAttr($data['type'], []);
        if ($type == 2) {
            $data['start'] = (new Express())->where('id', $data['start'])->value('name');
        }
        $data['annex_information_images'] = explode(',', $data['annex_information_images']);
        if (!empty($data['annex_information_images'])) {
            foreach ($data['annex_information_images'] as &$v) {
                $v = XypHelper::xyb_full_url($v);
            }
        }
        $data['annex_information_images'] = implode(',', $data['annex_information_images']);
        $data['express'] = !empty($data['express']) ? json_decode($data['express']) : [];
        $this->success('请求成功', $data);
    }

    /**
     * desc:订单确认完成:<1>订单状态;<2>增加收益记录;<3>更新用户钱包数据;<4>会员余额变动数据
     * param:order_id 订单id
     */
    public function confirm_complete()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->param();
        $time = time();
        $orderObj = $this->model->get($param['orderid']);
        if ($orderObj['status'] == 3) {
            $this->error('已签收');
        }
        $server_info = (new Server())->where([
            'agent_id' => $orderObj['agent_id'],
            'server_name' => $orderObj['type_text'],
        ])->field('agent_profit,receive_profit,platform_profit')->find();
        $walletsModel = new Wallets();
        $platform_wallets_info = $walletsModel->where([
            'user_id' => 1,
            'type' => '3',
        ])->find();
        $bind_agent_user_id = (new AdminBelong())->where([
            'admin_id' => $orderObj['agent_id'],
        ])->value('bind_agent_user_id');
        $agent_wallets_info = $walletsModel->where([
            'user_id' => $bind_agent_user_id,
            'type' => '2',
        ])->find();
        $receive_wallets_info = $walletsModel->where([
            'user_id' => $orderObj['receive_id'],
            'type' => '1',
        ])->find();
        $tem_platform_profit = bcmul($orderObj['total_fee'], $server_info['platform_profit'], 2);
        $platfrom_profit = bcmul($tem_platform_profit, 0.01, 3);
        $platfrom_profit = substr($platfrom_profit, 0, -1);

        $tem_agent_profit = bcmul($orderObj['total_fee'], $server_info['agent_profit'], 2);
        $agent_profit = bcmul($tem_agent_profit, 0.01, 3);
        $agent_profit = substr($agent_profit, 0, -1);

        $tem_receive_profit = bcmul($orderObj['total_fee'], $server_info['receive_profit'], 2);
        $receive_profit = bcmul($tem_receive_profit, 0.01, 3);
        $receive_profit = substr($receive_profit, 0, -1);
        $reduce_platform = bcsub($orderObj['total_fee'], $platfrom_profit, 2);
        $reduce_agent = bcsub($reduce_platform, $agent_profit, 2);

        $reduce_profit = bcsub($reduce_agent, $receive_profit, 2);
        if ($reduce_profit == 0.01) {
            $receive_profit = $receive_profit + 0.01;
        } elseif ($reduce_profit == 0.02) {
            $receive_profit = $receive_profit + 0.01;
            $agent_profit = $agent_profit + 0.01;
        } elseif ($reduce_profit == 0.03) {
            $receive_profit = $receive_profit + 0.01;
            $agent_profit = $agent_profit + 0.01;
            $platfrom_profit = $platfrom_profit + 0.01;
        }
        /*更新用户钱包数据*/
        $add_data = array();
        $edit_data = array();

        if (!$platform_wallets_info) {
            $add_data[] = [
                'user_id' => 1,
                'type' => '3',
                'total_income' => $platfrom_profit,
                'app_plat' => $param['app_plat'],
                'can_withdrawal_amount' => $platfrom_profit,
            ];
        } else {
            $edit_data[] = [
                'id' => $platform_wallets_info['id'],
                'total_income' => bcadd($platfrom_profit, $platform_wallets_info['total_income'], 2),
                'can_withdrawal_amount' => bcadd($platfrom_profit, $platform_wallets_info['can_withdrawal_amount'], 2),
            ];
        }

        if (!$agent_wallets_info) {
            $add_data[] = [
                'user_id' => $bind_agent_user_id,
                'type' => '2',
                'total_income' => $agent_profit,
                'app_plat' => $param['app_plat'],
                'can_withdrawal_amount' => $agent_profit,
            ];
        } else {
            $edit_data[] = [
                'id' => $agent_wallets_info['id'],
                'total_income' => bcadd($agent_profit, $agent_wallets_info['total_income'], 2),
                'can_withdrawal_amount' => bcadd($agent_profit, $agent_wallets_info['can_withdrawal_amount'], 2),
            ];
        }

        if (!$receive_wallets_info) {
            $add_data[] = [
                'user_id' => $orderObj['receive_id'],
                'type' => '1',
                'total_income' => $receive_profit,
                'app_plat' => $param['app_plat'],
                'can_withdrawal_amount' => $receive_profit,
            ];
        } else {
            $edit_data[] = [
                'id' => $receive_wallets_info['id'],
                'total_income' => bcadd($receive_profit, $receive_wallets_info['total_income'], 2),
                'can_withdrawal_amount' => bcadd($receive_profit, $receive_wallets_info['can_withdrawal_amount'], 2),
            ];
        }
        Db::startTrans();
        try {
            /*更新订单状态*/
            $this->model->save(
                [
                    'status' => 3,
                    'complete_time' => $time,
                ],
                ['id' => $param['orderid']]
            );
            /*增加收益记录*/
            (new Profit())->save([

            ]);
            /*更新用户钱包数据*/
            if (!empty($add_data)) {
                $walletsModel->saveAll($add_data);
            }
            if (!empty($edit_data)) {
                $walletsModel->saveAll($edit_data);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $orderInfo = $orderObj;
        $wechatInfo = (new UserPlat())->alias('plat')
            ->where([
                'plat.user_id' => $orderInfo['receive_id'],
            ])
            ->join('xyb_user_wechat wechat', 'plat.wechat_id = wechat.id')
            ->field('wechat.openid,wechat.nickname,plat.mobile')->find();
        if ($orderInfo['type'] == 1) {
            $orderInfo['tips'] = '校园跑腿';
        } else if ($orderInfo['type'] == 2) {
            $orderInfo['tips'] = '快递代取';
        } else if ($orderInfo['type'] == 4) {
            $orderInfo['tips'] = '租借服务';
        }

        $server_name = $this->model->getTypeTextAttr($orderInfo['type'], $orderInfo);
        $where = [
            'server_name' => $server_name,
            'agent_id' => $orderInfo['agent_id'],
        ];
        $receive_profit = (new Server())->where($where)->value('receive_profit');
        $tem = bcmul($orderInfo['total_fee'], $receive_profit, 2);
        $total_fee = bcmul($tem, 0.01, 2);
        $data = [
            'openid' => $wechatInfo['openid'],
            'form_id' => 3676,
            'template_id' => $this->configObj->order_complete,
            'page' => '/pages/Component/Module/Receiver/Program/order/detail/index?id=' . $orderInfo['id'],
            'data' => [
                'thing10' => array(
                    'value' => $orderInfo['tips']
                ),
                'number1' => array(
                    'value' => $orderInfo['order_no']
                ),
                'time6' => array(
                    'value' => date('Y-m-d H:i:s', time()),
                ),
                'amount11' => array(
                    'value' => $total_fee
                ),
                'thing5' => array(
                    'value' => '用户确认收货,佣金已到账'
                ),

            ],
        ];
        $push_result = (new WechatMiniPush())->PushOneMsg($data);
        $push_result = json_decode($push_result, true);
        $order_result = $orderInfo;
        $order_type = '校园跑腿';
        if ($order_result['type'] == 1) {
            $order_type = '校园跑腿';
        } else if ($order_result['type'] == 2) {
            $order_type = '快递代取';
        } else if ($order_result['type'] == 4) {
            $order_type = '租借服务';
        }

        //查出校区
        $agent_info = (new AdminBelong())->where('admin_id', $order_result['agent_id'])->value('agent_area');
        if ($push_result['errcode'] == 0) {
            $userWechatObj = (new UserPlat())->alias('plat')
                ->where('plat.user_id', $orderInfo['receive_id'])
                ->join('xyb_user_wechat wechat', 'wechat.id = plat.wechat_id')
                ->field('wechat.nickname,wechat_id,wechat.openid,wechat.unionid')
                ->find();
            $insert_data = [
                'type' => '订单完成通知:用户确认收货',
                'agent_id' => $order_result['agent_id'],
                'order_id' => $order_result['id'],
                'errmsg' => $push_result['errmsg'],
                'user_id' => $orderInfo['receive_id'],
                'wechat_id' => $userWechatObj['wechat_id'],
                'desc' => '订单id:' . $order_result['id'] . '推送订单完成通知给微信昵称:' . $userWechatObj['nickname'] . '消息成功,校区名称:' . $agent_info . '--订单类型：' . $order_type,
                'createtime' => time(),
                'openid' => $userWechatObj['openid'],
                'unionid' => $userWechatObj['unionid'],
                'data' => json_encode([
                    'thing10' => array(
                        'value' => $orderInfo['tips']
                    ),
                    'number1' => array(
                        'value' => $orderInfo['order_no']
                    ),
                    'time6' => array(
                        'value' => date('Y-m-d H:i:s', time()),
                    ),
                    'amount11' => array(
                        'value' => $total_fee
                    ),
                    'thing5' => array(
                        'value' => '用户确认收货,佣金已到账'
                    ),

                ]),
                'status_text' => '推送成功',
            ];
            (new MiniPushMessageLog())->create($insert_data);
        } else {
            $userWechatObj = (new UserPlat())->alias('plat')
                ->where('plat.user_id', $orderInfo['receive_id'])
                ->join('xyb_user_wechat wechat', 'wechat.id = plat.wechat_id')
                ->field('wechat.nickname,wechat_id,wechat.openid,wechat.unionid')
                ->find();
            $insert_data = [
                'type' => '订单完成通知:用户确认收货',
                'agent_id' => $order_result['agent_id'],
                'order_id' => $order_result['id'],
                'errmsg' => $push_result['errmsg'],
                'user_id' => $orderInfo['receive_id'],
                'wechat_id' => $userWechatObj['wechat_id'],
                'desc' => '订单id:' . $order_result['id'] . '推送订单完成通知给微信昵称:' . $userWechatObj['nickname'] . '消息失败,失败原因:' . $push_result['errmsg'] . '校区名称:' . $agent_info . '--订单类型：' . $order_type,
                'createtime' => time(),
                'openid' => $userWechatObj['openid'],
                'unionid' => $userWechatObj['unionid'],
                'data' => json_encode([
                    'thing10' => array(
                        'value' => $orderInfo['tips']
                    ),
                    'number1' => array(
                        'value' => $orderInfo['order_no']
                    ),
                    'time6' => array(
                        'value' => date('Y-m-d H:i:s', time()),
                    ),
                    'amount11' => array(
                        'value' => $total_fee
                    ),
                    'thing5' => array(
                        'value' => '用户确认收货,佣金已到账'
                    ),

                ]),
                'status_text' => '推送失败,原因:' . $push_result['errmsg'],
            ];
            (new MiniPushMessageLog())->create($insert_data);
        }
        $this->success('操作成功');
    }


    /**
     * desc:订单状态
     */
    public function status()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $id = $this->request->param('orderid');
        $this->success('请求成功', ['status' => $this->model->where('id', $id)->value('status')]);
    }

    /**
     * desc:取消订单
     */
    public function cancel()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $apiclient_cert_path = ROOT_PATH . 'addons' . DS . 'epay' . DS . 'certs' . DS . 'apiclient_cert.pem';
        $apiclient_cert_contents = file_get_contents($apiclient_cert_path);
        if (!$apiclient_cert_contents) {
            $this->error('请上传微信支付API证书cert');
        }

        $apiclient_key_path = ROOT_PATH . 'addons' . DS . 'epay' . DS . 'certs' . DS . 'apiclient_key.pem';
        $apiclient_key_contents = file_get_contents($apiclient_key_path);
        if (!$apiclient_key_contents) {
            $this->error('请上传微信支付API证书key');
        }

        $orderid = $this->request->param('orderid');
        $orderObj = $this->model->get($orderid);
        if ($orderObj['status'] == 2) {
            $this->error('接单员已接单,取消订单');
        }
        if ($orderObj['status'] == 4) {
            $this->error('后台已取消订单');
        }
        $orderInfo = $this->model->get($orderid);//退款订单信息

        if ($orderInfo['pay'] == 0) {
            $this->model->save(['status' => '4'], ['id' => $orderid]);
            $this->success('取消成功');
        }

        $notifyurl = $this->request->domain() . '/api/order/refundnotifyx';//退款回调地址

        //直接调用退款方法传参即可
        $response = WxPay::submitRefund($orderInfo['total_fee'], $orderInfo['total_fee'], $orderInfo['order_no'], xyb_get_refund_sn($orderInfo['user_id']), 'wechat', '自己取消订单', $notifyurl, '', 'miniapp');
        if (isset($response->return_code) && $response->return_code == 'SUCCESS') {
            $this->model->save([
                'status' => 4
            ], [
                'order_no' => $response->out_trade_no
            ]);
            $redis = new Redis();
            $redis = $redis->handler();
            $domain = $_SERVER['HTTP_HOST'];
            $redis->rpop($domain . '_order_number_' . $orderid);
            $this->success('取消成功');
        } else {
            $this->error('取消失败');
        }
    }

    /**
     * desc:接单员查看隐私数据
     */
    public function receiver_order_detail()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $id = $this->request->param('orderid');
        $orderObj = $this->model->get($id);
        $data = array();
        switch ($orderObj['type']) {
            case 2:
                $data['information'] = $orderObj['information'];
                $data['annex_information_images'] = !empty($orderObj['annex_information_images']) ? explode(',', $orderObj['annex_information_images']) : [];
                foreach ($data['annex_information_images'] as &$v) {
                    $v = XypHelper::xyb_full_url($v);
                }
                break;
            case 3:
                $data['game_id'] = $orderObj['game_id'];
                break;
        }
        if ($orderObj['app_plat'] == 'MP-WEIXIN') {
            $wechatInfo = Db::name('xyb_user_plat')
                ->alias('u_p')
                ->where('u_p.user_id', $orderObj['user_id'])
                ->join('xyb_user_wechat u_w', 'u_w.id = u_p.wechat_id')
                ->field('u_p.mobile')
                ->find();
            $data['user_mobile'] = $wechatInfo['mobile'];
        } else {
            $data['user_mobile'] = '';
        }

        $this->success('请求成功', $data);
    }

    /**
     * @throws \Exception
     * @desc 调起小程序微信支付
     */
    public function wx_minapp_pay_immediately()
    {

        /**
         * 回调地址:https://www.example.com/addons/epay/api/notifyx/type/wechat/out_trade_no/43
         */
        $param = $this->request->param();
        $type = 'wechat';
        $notifyurl = $this->request->root(true) . '/api/xyb/wx_pay/notifyx/type/' . $type . '/out_trade_no/' . $param['orderid'];
        $returnurl = $this->request->root(true) . '/addons/epay/api/returnx/type/' . $type . '/out_trade_no/' . $param['orderid'];
        $orderInfo = $this->model->where('id', $param['orderid'])->find();
        $user_id = $orderInfo['user_id'];
        if ($param['amount'] != $orderInfo['total_fee']) {
            $this->error('支付价格和订单价格不一致');
        }
        $openidResult = Db::name('xyb_user_plat')
            ->where('u_p.user_id', $user_id)
            ->alias('u_p')
            ->join('xyb_user_wechat u_w', 'u_p.wechat_id = u_w.id')
            ->field('u_w.openid')
            ->find();
        if (!$openidResult['openid']) {
            $openid = (new UserBelong())->where('user_id', $user_id)->value('openid');
        } else {
            $openid = $openidResult['openid'];
        }
        if (!$openid) {
            $this->error('openid缺失');
        }
//        $data = [
//            'amount'=>$param['amount'],
//            'orderid'=>$param['orderid'],
//            'type'=>"wechat",
//            'title'=>"订单标题,订单号:".$param['orderid'],
//            'notifyurl'=>$notifyurl,
//            'returnurl'=>$returnurl,
//            'method'=>"miniapp",
//            'openid'=>"用户的OpenID",
//            'auth_code'=>"验证码"
//        ];
//        $param['amount'] = 0.01;
        switch ($orderInfo['type']) {
            case 1:
                $name = '校园跑腿';
                break;
            case 2:
                $name = '快递代取';
                break;
            case 4:
                $name = '租借服务';
                break;
            default:
                $name = '其他';
        }
        $miniapp_title = $this->configObj->miniapp_title;
        $title = $name . ' —— ' . $miniapp_title;

        $data = Service::submitOrder($orderInfo['total_fee'], $orderInfo['order_no'], $type, $title, $notifyurl, $returnurl, 'miniapp', $openid);
        $this->model->save([
            'wechat_pay_prepare' => json_encode($data)
        ], [
            'id' => $param['orderid']
        ]);
        //测试发送公众号推送消息
        $this->success('请求成功', $data);
    }






    /**
     * [do_pay 进行支付]
     * @Author   ZhouYunpeng
     * @DateTime 2020-04-11
     * @param int $order_id 订单号
     * @param varchar $type 支付方式
     */
    public function doPay()
    {
        $order_id = $this->request->request('order_id');
        $type = $this->request->request('type');
        $method = $this->request->request('method');


        if (!$order_id || !$type || !$method) {
            $this->error(__('Invalid parameters'));
        }
        $order = $this->model->where('id', $order_id)->find();
//        $order = OrderModel::get(['id' => $order_id]);
//        if (!$order){
//            $this->error('订单不存在');
//        }

        if ($order['pay_status'] == 1) {
            $this->error('订单已支付');
        }

        try {
            if ($type == 'wechatpay') {
                //创建支付对象
                $config = Service::getConfig('wechat');
                if ($method == 'wap') {
                    $config['return_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/addons/epay/api/returnx/type/wechat/order_id/' . $order_id . '/out_trade_no/' . $order['out_trade_no'];
                }
                $pay = Pay::wechat($config);
                $params = [
                    'out_trade_no' => $order['out_trade_no'], //你的订单号
                    'body' => $order['product_name'],
                    'total_fee' => $order['order_amount'] * 100, //单位分
                    // 'total_fee'    => 1,             //单位分
                ];
                switch ($method) {
                    case 'mp':
                        //公众号支付
                        //公众号支付必须有openid
                        $params['openid'] = $user['openid'];
                        $result = $pay->mp($params);
                        break;
                    case 'wap':
                        //手机网页支付,跳转
                        $params['spbill_create_ip'] = $this->request->ip();
                        $wapres = $pay->wap($params);
                        $result = $wapres->getTargetUrl();
                        break;
                    case 'app':
                        //APP支付,直接返回字符串
                        $result = $pay->app($params);
                        break;
                    case 'miniapp':
                        //小程序支付,直接返回字符串
                        //小程序支付必须要有openid
                        $params['openid'] = $user['miniapp_openid'];
                        $result = $pay->miniapp($params);
                        break;
                    default:
                }
                $this->success('wechatpay', $result);
            } elseif ($type == 'alipay') {
                //创建支付对象
                $config = Service::getConfig('alipay');
                if ($method == 'wap') {
                    $config['return_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/addons/epay/api/returnx/type/alipay/order_id/' . $order_id . '/out_trade_no/' . $order['out_trade_no'];
                }
                $pay = Pay::alipay($config);
                $params = [
                    // 'total_amount'    => 0.01,                //金额
                    'total_amount' => $order['order_amount'], //金额
                    'out_trade_no' => $order['out_trade_no'], //订单号
                    'subject' => $order['product_name'],
                ];

                switch ($method) {
                    case 'wap':
                        //手机网页支付
                        $wapres = $pay->wap($params);
                        $result = $wapres->getContent();
                        break;
                    case 'app':
                        //APP支付
                        $appres = $pay->app($params);
                        $result = $appres->getContent();
                        break;
                    default:
                }
                $this->success('alipay', $result);

            } elseif ($type == 'balance') {
                //分销商端余额支付
                //是否绑定第三方商品
                if ($order['is_third']) {
                    $third_goods = Db::name('thirdparty_goods')->where(['goods_id' => $order['goods_id']])->find();
                    switch ($third_goods['system_id']) {
                        case '1':
                            $otc = new \app\common\model\thirdparty\Oct();
                            $result = $otc->createOrder($order);
                            break;
                        case '2':
                            $pft = new \app\common\model\thirdparty\Pft();
                            $result = $pft->createOrder($order);
                            break;
                        case '3':
                            $zyb = new \app\common\model\thirdparty\Zyb();
                            $result = $zyb->createOrder($order);
                            break;
                        default:
                            # code...
                            break;
                    }
                    $order->balancePay($order['id'], $order['user_id']);
                    if ($result['code']) {
                        $voucherModel = new Voucher();
                        $voucherModel->sendSms($order);
                        if ($user['openid']) {
                            $order->wechatNotice($user['openid'], $order, $pagepath = 1);
                        }
                    } else {
                        //第三方未出票自动退款
                        $refundModel = new Refund();
                        $refundModel->automaticRefund($order);
                    }
                    $this->success('支付成功', ['order_id' => $order['id']]);

                } else {
                    $result = $order->balancePay($order['id'], $order['user_id']);
                    Voucher::notify($order['id']);
                    $goods = Db::name('goods')->field('category_id')->find($order['goods_id']);
                    if ($goods['category_id'] == 2) {
                        //一日游通知
                        $order->routeNotice($order);
                    }
                    if ($user['openid']) {
                        $order->wechatNotice($user['openid'], $order, $pagepath = 1);
                    }

                    $this->success('支付成功', ['order_id' => $order['id']]);
                }
            } else {
                $this->error('支付方式不正确');
            }
        } catch (Exception $e) {

            $this->error($e->getMessage());
        }
    }
}